﻿var _global = this;

(function() {
    function BoxesGame(canvas, size) {
        _canvas = canvas;
        _size = size;
        _height = canvas.offsetHeight;
        _width = canvas.offsetWidth;
    }

    _global.BoxesGame = BoxesGame;

    var _points = [];
    var _lines = [];
    var _canvas;
    var _ctx;
    var _fps = 8;
    var _size;
    var _height;
    var _width;

    BoxesGame.prototype.start = function() {
        _ctx = _canvas.getContext('2d');

        this.buildGrid();

        setInterval(this.draw, 1000 / _fps);

        _canvas.onmousedown = function(event) {
            try {
                var x = event.clientX - _canvas.offsetLeft;
                var y = event.clientY - _canvas.offsetTop;

                for (var i in _lines) {
                    var l = _lines[i];
                    if (l.isHit(x, y)) {
                        l.select();
                        break;
                    }
                }
            }
            catch (e) {
                this.Log(e);
            }
        };
    }

    BoxesGame.prototype.buildGrid = function() {
        for (x = 0; x < _size; x++) {
            _points[x] = [];
            for (y = 0; y < _size; y++) {
                var p = new Point(x, y, this.getXGap, this.getYGap);
                _points[x][y] = p;

                if (x != 0) {
                    _lines[_lines.length] = new Line(_points[x - 1][y], p);
                }

                if (y != 0) {
                    _lines[_lines.length] = new Line(_points[x][y - 1], p);
                }
            }
        }
    }

    BoxesGame.prototype.draw = function() {
        try {
            _ctx.clearRect(0, 0, _width, _height);
            for (x = 0; x < _points.length; x++) {
                for (y = 0; y < _points[x].length; y++) {
                    _points[x][y].draw(_ctx);
                }
            }
            for (var i in _lines) {
                _lines[i].draw(_ctx);
            }
        }
        catch (e) {
            this.Log(e);
        }
    }

    BoxesGame.prototype.getXGap = function() { return Math.floor(_width / (_size + 2)); }
    BoxesGame.prototype.getYGap = function() { return Math.floor(_height / (_size + 2)); }
    BoxesGame.prototype.Log = function(e) { }

})();

(function() {
    function Box(top, bottom, left, right) {
        _top = top;
        _bottom = bottom;
        _left = left;
        _right = right;
    }

    var _top;
    var _bottom;
    var _left;
    var _right;

    Box.prototype.render()
    {
    }
})();